<template>
    <el-dialog :title="dialogStatus | titleFilter" :close-on-click-modal="false" width="1000px" :visible.sync="visible">
        <el-form ref="temp" :model="temp" :rules="rule" label-width="150px" @keyup.enter.native="dataFormSubmit()">

            <el-row :gutter="0">
                <el-col :span="12" :offset="0">
                    <el-form-item label="园区/楼栋/单元/楼层" prop="park_id">
                        <el-cascader v-model="temp.park_id" :options="park_options" :props="props_opt" style="width:100%"
                            @change="park_change" />
                    </el-form-item>

                </el-col>

                <el-col :span="12">
                    <el-form-item label="房屋" prop="house_id">
                        <el-select v-model="temp.house_id" placeholder="请选择" @change="house_change">
                            <el-option v-for="item in house_options" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="0">
                <el-col :span="12" :offset="0">
                    <el-form-item label="签订人信息" prop="customerId">
                        <el-select clearable v-model="temp.customerId" filterable :filter-method="fileCustomer" placeholder="请选择"
                            @change="getCustomer">
                            <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" :offset="0">
                    <div class="customer_info" v-if="temp.customer_info.type == '1' ">
                        <span>身份证号:{{temp.customer_info.idcard}}</span><span>手机号:{{temp.customer_info.mobile}}</span>
                    </div>
                    <div class="customer_info" v-else>
                        <span>法人姓名:{{temp.customer_info.legalPerson}}</span><span>纳税人识别号:{{temp.customer_info.taxNumber}}</span>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="0">
                <el-col :span="12">

                    <el-form-item label="合同类型" prop="contractType">
                        <el-select v-model="temp.contractType" placeholder="请选择">
                            <el-option v-for="(item, key) in contractType" :key="key" :label="item" :value="key" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="签订时间" prop="signDate">
                        <el-date-picker v-model="temp.signDate" type="date" value-format="yyyy-mm-dd" placeholder="选择签订时间" clearable />
                    </el-form-item>

                    <el-form-item label="结束时间" prop="validDate">
                        <el-date-picker v-model="temp.validDate" type="date" value-format="yyyy-MM-dd" placeholder="选择签订时间" clearable />
                    </el-form-item>

                    <el-form-item label="合同金额" prop="money">
                        <el-input v-model="temp.money" type="number" placeholder="合同金额">
                            <el-button slot="append">元/月</el-button>
                        </el-input>
                    </el-form-item>

                </el-col>
                <el-col :span="12">
                    <el-form-item label="收费周期" prop="chargeType">
                        <el-select v-model="temp.chargeType" placeholder="请选择">
                            <el-option v-for="(item, key) in chargeCycle" :key="key" :label="item" :value="key" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="开始时间" prop="effectDate">
                        <el-date-picker v-model="temp.effectDate" type="date" value-format="yyyy-MM-dd" placeholder="选择签订时间" clearable />
                    </el-form-item>

                    <el-form-item label="租赁/出售保证金" prop="depositMoney" label-width="160px">
                        <el-input v-model="temp.depositMoney" type="number" placeholder="租赁/出售保证金" />
                    </el-form-item>

                    <el-form-item label="收款账户" prop="accountId">
                        <el-select v-model="temp.accountId" placeholder="请选择收款账户" @change="account_change">
                            <el-option v-for="item in account_options" :key="item.id" :label="item.accountName" :value="item.id" />
                        </el-select>
                    </el-form-item>

                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">

                </el-col>
                <el-col :span="24" :offset="0">
                    <el-form-item label="合同照片">
                        <el-upload :file-list="fileList" class="avatar-uploader" :action="action" :before-remove="beforeRemove"
                            :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess" :data="img_param" :headers="img_param"
                            accept=".png, .jpg, .jpeg">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-form-item label="备注" prop="remark">
                <el-input v-model="temp.remark" placeholder="备注" />
            </el-form-item> -->

        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">
                取消
            </el-button>
            <el-button type="primary" @click="dataFormSubmit">
                确认
            </el-button>
        </span>
    </el-dialog>
</template>
<script>
import { createContract, updateContract, getHouseListAll, updateHouseTree, getHouseTree, getCustomerListAll, getAccountList } from '@/api/assets'// 请求数据
import { houseState, houseType, houseFunction } from '@/utils/enum' // 字典
import { validatPhone, validatContactID, isNunberFloat } from '@/utils/validate'
import { treeDataTranslate, formatDate, deepClone, toDate, date_utils } from '@/utils'
import { contractType, chargeCycle } from '@/utils/enum'
import { getToken } from '@/utils/auth'
export default {
    filters: {
        // 过滤弹框的标题
        titleFilter (type) {
            const textMap = {
                create: '新增',
                update: '修改'
            }
            return textMap[type]
        },
        // 新增属性名
        // 过滤弹框的标题
        lableFilter (type) {
            const textMap = ['楼栋', '单元', '楼层']
            return textMap[type]
        }
    },
    data () {
        var validatPhone_ = (rule, value, callback) => {
            const vilidat = validatPhone(value)
            if (!vilidat) {
                callback(new Error('请检查手机号是否正确'))
            }
            callback()
        }
        var validatContactID_ = (rule, value, callback) => {
            const vilidat = validatContactID(value)
            if (!vilidat) {
                callback(new Error('请检查身份证号格式是否正确'))
            }
            callback()
        }
        return {
            fileList: [],
            fileListPath: [], //图片地址
            action: `${process.env.VUE_APP_BASE_API}/admin/sys/oss/manage/upload `,
            visible: false,
            dialogStatus: '', // 弹框新增或者修改
            park_options: [], // 园区list
            house_options: [],//房屋list
            account_options: [],//合同
            props_opt: {
                label: 'storeyName',
                value: 'id',
                children: 'list'
            },
            contractType: contractType,
            chargeCycle: chargeCycle,
            customerList: [],
            customerListData: [],//复制一份可以清空后还是正常项

            temp: { // 表单数据
                id: '',
                park_id: '', // 园区/楼栋/单元/层 id
                park_node: '', // 园区/楼栋/单元/层 节点
                house_id: '',//房屋id
                house_node: '',//房屋 节点
                customerId: '',//签订人 id
                customer_info: '',// 签订人 节点
                contractType: '1',//合同类型
                chargeType: '1',//收费周期
                signDate: formatDate('-'),//签订时间
                effectDate: "", //生效时间
                validDate: "",//结束时间
                depositMoney: "",//出售保证金
                money: "",  //合同金额
                accountId: "", //收款账户id
                accountId_node: '',//收款账户节点
                contractPic: "", // 合同附件
            },
            rule: {
                park_id: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                house_id: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                house_id: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                signDate: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                effectDate: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                // validDate: [
                //     { required: true, message: '不能为空', trigger: 'blur' }
                // ],
                depositMoney: [
                    {
                        required: false,

                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value && !isNunberFloat(value)) {
                                callback(new Error('只能输入至多含有两位小数的数字'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'change'
                    }
                ],
                money: [
                    {
                        required: true,
                        message: '不能为空'
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value && !isNunberFloat(value)) {
                                callback(new Error('只能输入至多含有两位小数的数字'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'change'
                    }
                ],
            },
            upData: null
        }
    },
    computed: {
        houseState_ () {
            const arr = []
            for (const key in houseState) {
                arr.push({
                    lable: houseState[key],
                    value: key
                })
            }
            return arr
        },
        houseType_ () {
            const arr = []
            for (const key in houseType) {
                arr.push({
                    lable: houseType[key],
                    value: key
                })
            }
            return arr
        },
        houseFunction_ () {
            const arr = []
            for (const key in houseFunction) {
                arr.push({
                    lable: houseFunction[key],
                    value: key
                })
            }
            return arr
        },

        img_param () {
            let token = getToken();
            return { token }
        }

    },
    created () {
    },
    methods: {
        // 初始化
        init (status, param) {
            // console.log(status)
            this.dialogStatus = status // 标题
            this.visible = true // 显示
            this[status](param) // 新增或者修改
            this.$nextTick(() => { // 重置表单
                this.$refs['temp'].clearValidate()
            })
            this.get_park()
            this.getCustomerList()
            this.getAccountList()
        },
        create (param) {
            this.resetTemp(param) // 清空表单
        },
        async update (param) {
            console.log("param", param)
            this.upData = param
            const data = Object.assign({}, param)// 从上一页带过来当前的数据
            //   const { data, code } = await getParkDetails({}, param.id) // 从后台获取当前的的数据
            // 成功



            this.temp.id = data.id
            //注释得几项再获取列表得时候整理
            // this.temp.park_id = data.parkId, // 园区/楼栋/单元/层 id
            // park_node: '', // 园区/楼栋/单元/层 节点
            // house_id: '',//房屋id
            // house_node: '',//房屋 节点
            // customerId: '',//签订人 id
            // customer_info: '',// 签订人 节点
            this.temp.contractType = data.contractType.toString()//合同类型
            this.temp.chargeType = data.chargeType.toString()//收费周期
            // this.temp.signDate = toDate(data.signDate)//签订时间
            // this.temp.effectDate = toDate(data.effectDate) //生效时间
            // this.temp.validDate = toDate(data.validDate)//结束时间
            this.temp.signDate = date_utils.formatDate(new Date(data.signDate))//签订时间
            this.temp.effectDate = date_utils.formatDate(new Date(data.effectDate)) //生效时间
            this.temp.validDate = date_utils.formatDate(new Date(data.validDate))//结束时间

            this.temp.depositMoney = data.depositMoney//出售保证金
            this.temp.money = data.money  //合同金额
            // accountId: "", //收款账户id
            // accountId_node: '',//收款账户节点
            this.contractPic = data.contractPic ? data.contractPic.split(',') : [] // 合同附件
        },
        // 获取园区tree
        async get_park () {
            const res = await getHouseTree().catch(e => { })
            // 失败
            if (!res) { this.listLoading = false; return }
            // 成功
            const { data, code, message } = res
            const options = treeDataTranslate(data, 'id', 'parentId')
            this.park_options = this.set_tree(options)

            if (this.dialogStatus == 'create') return;

            const arr = []
            this.park_options.forEach((item, index) => {
                if (item.parkId == this.upData.parkId) arr.push(item.id)
            })
            arr.push(this.upData.buildingId)
            if (this.upData.unitId) arr.push(this.upData.unitId)
            arr.push(this.upData.floorId)
            this.temp.park_id = arr

            if (this.dialogStatus == 'create') return;
            this.park_change()
        },
        set_tree (data) {
            function treeArr (arr) {
                arr.forEach((item, index) => {
                    if (item.type == 3) delete item.list
                    if (item.list && item.list.length > 0) {
                        treeArr(item.list)
                    }
                })
                return arr
            }
            const res = treeArr(data)
            return res
        },
        //获取签订人
        async getCustomerList () {
            let param = {
                parkId: this.temp.park_node.length > 0 ? this.temp.park_node[0].parkId : ''
            }
            const res = await getCustomerListAll(param)
            const { data, code, message } = res
            this.customerList = data
            this.customerListData = data.concat([])
            // console.log("签订人",data)

            if (this.dialogStatus == 'create') return;

            let node = data.filter(item => {
                return item.id == this.upData.customerId
            })
            this.temp.customerId = node[0].id
            this.temp.customer_info = node[0]
            // customerId: '',//签订人 id
            // customer_info: '',// 签订人 节点
        },
        //获取合同列表
        async getAccountList () {
            const res = await getAccountList()
            const { data, code, message } = res
            this.account_options = data
            // console.log("合同", data)

            if (this.dialogStatus == 'create') return;
            let node = data.filter(item => {
                return item.id == this.upData.accountId
            })
            this.temp.accountId = node[0].id
            this.temp.accountId_node = node[0]
            // accountId: "", //收款账户id
            // accountId_node: '',//收款账户节点
        },
        fileCustomer (val) {
            if (val) {
                this.customerList = this.customerList.filter(item => {
                    return item.customerName.includes(val) || item.mobile.includes(val)
                })
            } else {
                this.customerList = this.customerListData
            }
        },
        // 获取房屋list
        // 查询房屋
        async getHouseListAll () {
            const params = Object.assign({
                parkId: this.temp.park_node[0] ? this.temp.park_node[0].parkId : '',
                buildingId: this.temp.park_node[0] ? this.temp.park_node[1].id : '',
                unitId: this.temp.park_node.length == 4 ? this.temp.park_node[2].id : "",
                floorId: this.temp.park_node.length == 4 && this.temp.park_node.length > 0 ? this.temp.park_node[3].id : this.temp.park_node[2]
            }, this.listQuery)
            // 请求
            const res = await getHouseListAll(params).catch(e => { })
            // 失败
            if (!res) { return }
            // 成功
            const { data, code, message } = res
            this.house_options = data

            if (this.dialogStatus == 'create') return;

            let node = data.filter(item => {
                return item.id == this.upData.houseId
            })
            this.temp.house_id = node[0].id
            this.temp.house_node = node[0]
            // / house_id: '',//房屋id
            // house_node: '',//房屋 节点
            // this.temp.house_id = ''
        },
        // 新增数据清空表单数据
        resetTemp (param) {
            this.temp = {
                id: '',
                park_id: '', // 园区/楼栋/单元/层 id
                park_node: '', // 园区/楼栋/单元/层 节点
                house_id: '',//房屋id
                house_node: '',//房屋 节点
                customerId: '',//签订人 id
                customer_info: '',// 签订人 节点
                contractType: '1',//合同类型
                chargeType: '1',//收费周期
                signDate: formatDate('-'),//签订时间
                effectDate: "", //生效时间
                validDate: "",//结束时间
                depositMoney: "",//出售保证金
                money: "",  //合同金额
                accountId: "", //收款账户id
                accountId_node: '',//收款账户节点
                contractPic: "", // 合同附件
            }

        },
        // 表单提交
        dataFormSubmit () {
            this.$refs['temp'].validate(async (valid) => {
                if (!valid) return
                console.log(this.temp.park_node)
                const params = {
                    'id': this.temp.id ? this.temp.id : '',
                    'parkId': this.temp.park_node[0].parkId, // 园区
                    'parkName': this.temp.park_node[0].parkName,
                    'buildingId': this.temp.park_node[1].id,
                    'buildingName': this.temp.park_node[1].storeyName,
                    'unitId': this.temp.park_node.length == 4 ? this.temp.park_node[2].id : '',
                    'unitName': this.temp.park_node.length == 4 ? this.temp.park_node[2].storeyName : '',
                    'floorId': this.temp.park_node.length == 4 ? this.temp.park_node[3].id : this.temp.park_node[2].id,
                    'floorName': this.temp.park_node.length == 4 ? this.temp.park_node[3].storeyName : this.temp.park_node[2].storeyName,
                    'houseId': this.temp.house_node.id,
                    'houseName': this.temp.house_node.name,
                    'customerId': this.temp.customer_info.id,
                    'customerName': this.temp.customer_info.customerName,
                    'customerType': this.temp.customer_info.type,
                    'customerMobile': this.temp.customer_info.mobile ? this.temp.customer_info.mobile : '',
                    'idcard': this.temp.customer_info.idcard ? this.temp.customer_info.idcard : '',
                    'legalPersonName': this.temp.customer_info.legalPerson ? this.temp.customer_info.legalPerson : '',
                    'taxNumber': this.temp.customer_info.taxNumber ? this.temp.customer_info.taxNumber : '',
                    'contractType': this.temp.contractType,
                    'chargeType': this.temp.chargeType,
                    'signDate': this.temp.signDate,
                    'effectDate': this.temp.effectDate,
                    'validDate': this.temp.validDate,
                    'money': this.temp.money,
                    'depositMoney': this.temp.depositMoney,
                    'accountId': this.temp.accountId_node.id,
                    'accountNo': this.temp.accountId_node.accountNumber,
                    'accountBank': this.temp.bankName,
                    'contractPic': this.fileListPath.join[','],
                }
                console.log(params)
                // 没有单元
                if (!params.unitId) {
                    delete params.unitId
                    delete params.unitName
                }
                const textMap = {
                    create: createContract, // 新增
                    update: updateContract // 修改
                }
                // 提交表单
                const { code, message } = await textMap[this.dialogStatus](params)
                // 成功
                this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 1500,
                    onClose: () => {
                        this.visible = false
                        this.$emit('getList')
                        this.$emit('getTree')
                    }
                })
            })
        },

        // ===>>>>>>>>>

        // 选择园区
        park_change (e) {
            // console.log(e, this.park_options)
            let park = this.park_options.filter((item, index) => {
                return item.id == this.temp.park_id[0]
            })
            let building = park[0].list.filter((item, index) => {
                return item.id == this.temp.park_id[1]
            })
            let unit = building[0].list.filter((item, index) => {
                return item.id == this.temp.park_id[2]
            })
            let floor = null;
            if (this.temp.park_id.length == 3) {
                floor = building[0].list.filter((item, index) => {
                    return item.id == this.temp.park_id[this.temp.park_id.length - 1]
                })
                this.temp.park_node = [park[0], building[0], floor[0]]
            }
            if (this.temp.park_id.length == 4) {
                floor = unit[0].list.filter((item, index) => {
                    return item.id == this.temp.park_id[this.temp.park_id.length - 1]
                })
                this.temp.park_node = [park[0], building[0], unit[0], floor[0]]
            }

            console.log("园区节点", this.temp.park_node)
            this.temp.house_id = ''
            this.getHouseListAll()
            this.getCustomerList()
        },
        //选择签订人
        getCustomer (val) {
            let info = this.customerList.filter(item => {
                return item.id == val
            })
            console.log("选择签订人", info)
            this.temp.customer_info = info[0]
        },
        //选择账户
        account_change (e) {
            console.log(e, this.account_options)
            let info = this.account_options.filter(item => {
                return item.id == e
            })
            console.log("选择账户", info)
            this.temp.accountId_node = info[0]
        },
        //选择房屋
        house_change (e) {
            let info = this.house_options.filter(item => {
                return item.id == e
            })
            console.log("选择房屋", info)
            this.temp.house_node = info[0]
        },
        // change
        change (e) {
            console.log(e)
        },
        beforeRemove (file, fileList) {
            console.log(file, fileList)
            fileList.forEach((item, index) => {
                if (file.uid === item.uid) {
                    this.fileListPath.splice(index, 1)
                }
            })
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 5MB!');
            }
            return isLt2M;
        },
        handleAvatarSuccess (res, file) {
            // this.temp.imgUrl = res.data
            if (res && res.code === 200) {
                // this.temp.idcardPicFront = URL.createObjectURL(file.raw);
                this.fileListPath.push(res.data.location)
                this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                    }
                });
            } else {
                this.$message.error(res.message);
            }
        }

    }
}
</script>

<style lang="scss">
.mod-menu {
    .menu-list__input,
    .icon-list__input {
        > .el-input__inner {
            cursor: pointer;
        }
    }
    &__icon-popover {
        width: 458px;
        overflow: hidden;
    }
    &__icon-inner {
        width: 478px;
        max-height: 258px;
        overflow-x: hidden;
        overflow-y: auto;
    }
    &__icon-list {
        width: 458px;
        padding: 0;
        margin: -8px 0 0 -8px;
        > .el-button {
            padding: 8px;
            margin: 8px 0 0 8px;
            > span {
                display: inline-block;
                vertical-align: middle;
                width: 18px;
                height: 18px;
                font-size: 18px;
            }
        }
    }
    .icon-list__tips {
        font-size: 18px;
        text-align: center;
        color: #e6a23c;
        cursor: pointer;
    }
}
.customer_info {
    line-height: 28px;
    display: flex;
    flex-flow: row;
    justify-content: space-around;
}
</style>
